package com.qdxwx.web.controller.user;

import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.page.PageRequest;
import com.qdxwx.common.utils.ObjectUtils;
import com.qdxwx.common.utils.TKServlet;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.service.card.CardCodeService;
import com.qdxwx.data.service.card.CardCourseService;
import com.qdxwx.data.service.card.CardService;
import com.qdxwx.data.service.course.CourseService;
import com.qdxwx.data.service.order.OrderDetailService;
import com.qdxwx.data.service.order.OrderService;
import com.qdxwx.data.service.user.UserBuyService;
import com.qdxwx.models.card.Card;
import com.qdxwx.models.card.CardCode;
import com.qdxwx.models.card.CardCodeQuery;
import com.qdxwx.models.card.CardCodeVO;
import com.qdxwx.models.course.Course;
import com.qdxwx.models.enums.*;
import com.qdxwx.models.order.Order;
import com.qdxwx.models.order.OrderDetail;
import com.qdxwx.models.user.User;
import com.qdxwx.web.controller.BaseController;
import com.qdxwx.web.utils.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 *
 * author developer
 */
@Controller
@RequestMapping("/user/course")
public class UserCourseCardController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(UserCourseCardController.class);
    @Autowired
    private CardService cardService;
    @Autowired
    private CardCodeService cardCodeService;
    @Autowired
    private CardCourseService cardCourseService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private CourseService courseService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private UserBuyService userBuyService;

    /**
     * 个人中心我的课程卡
     */
    @RequestMapping("/card.html")
    public String cardList(HttpServletRequest request, ModelMap mmap) {
        CardCodeQuery cardCodeQuery = new CardCodeQuery();
        cardCodeQuery.setUserId(LoginUser.getUserId(request));
        cardCodeQuery.setTypeId(1);
        List<CardCodeVO> userCardCodeList = cardCodeService.getVOList(cardCodeQuery, PageRequest.form(request));
        mmap.put("userCardCodeList", userCardCodeList);
        return getViewPath("ucenter/uc-course-card");
    }

    /**
     * 虚拟卡信息激活
     */
    @RequestMapping("/card/active.html")
    public String courseCardActive() {

        return getViewPath("ucenter/uc-course-card-active");
    }

    /**
     * 虚拟卡信息激活
     */
    @RequestMapping("/card/active.json")
    @ResponseBody
    public AjaxResult courseCardActivePost(HttpServletRequest request) {
        User user = LoginUser.getUser(request);
        if (user == null) return AjaxResult.error("登录超时");
        String code = TKString.trim(request.getParameter("cardCode"));
        String pwd = TKString.trim(request.getParameter("cardCodePassword"));
        CardCode cardCode = cardCodeService.getByCode(code, pwd);
        if (cardCode == null) {
            return AjaxResult.error("卡号或密码错误，请确认，谢谢！");
        }
        if (cardCode.getStatus().equals(CardStatus.USED.toString())) {
            return AjaxResult.error("该卡已被使用，不能再次使用！");//已经使用
        } else if (cardCode.getStatus().equals(CardStatus.CLOSE.toString())) {
            return AjaxResult.error("该卡已作废，不能再次使用！");//已关闭
        } else if (cardCode.getStatus().equals(CardStatus.OVERDUE.toString())) {
            return AjaxResult.error("该卡已过期，不能再次使用！");//已过期
        }
        Card card = cardService.get(cardCode.getCardId());
        if (card.getTypeId() != 1) {
            return AjaxResult.error("卡号或密码错误，请确认输入是否正确！");//类型不匹配
        }
        //不在有效期内
        LocalDate nowDate = LocalDate.now();
        if (nowDate.isBefore(card.getBeginDate()) || nowDate.isAfter(card.getEndDate())) {
            return AjaxResult.error("该卡不在有效期内，请确认！谢谢");
        }

        //查找未过期的 课程， 存在的课程
        List<Integer> courseIds = cardCourseService.getCourseIds(cardCode.getCardId());
        if (courseIds == null || courseIds.size() < 1) {
            logger.info("该卡未关联任何课程:" + cardCode);
            return AjaxResult.error("该卡未关联任何课程，请与本网管服联系！");
        }
        // 拼装订单数据
        Order order = new Order();
        // 下单时间
        LocalDateTime date = LocalDateTime.now();
        order.setCreateTime(date);// 下单时间
        order.setUserId(user.getUserId());
        order.setUserName(user.getDisplayName());
        order.setOrderNo(orderService.createOrderNo(user.getUserId()));// 交易请求号
        order.setStatus(OrderStatus.SUCCESS.toString());// 交易装态,成功状态的
        order.setPayType(PayType.CARD.toString());// 支付类型课程卡
        order.setReqChannel(ReqChannel.WEB.toString());
        order.setReqIp(TKServlet.getIpAddr());
        order.setOrderType(OrderType.COURSE.toString());//订单类型
        order.setOrderAmount(0); // 原始金额
        order.setCouponAmount(0);// 优惠金额
        order.setPayAmount(0);// 实际支付金额
        order.setDescription("课程卡使用(" + cardCode.getCardCode() + ")");// 账户历史内容描述
        order.setPayTime(date);// 支付时间
        order.setCompanyId(user.getCompanyId());
        // 添加订单
        orderService.insert(order);
        // 添加流水表
        for (Integer courseId : courseIds) {
            Course cou = courseService.get(courseId);
            if (ObjectUtils.isNull(cou)) {
                continue;
            }
            // 创建流水
            OrderDetail orderDetail = new OrderDetail();
            // 用户id
            orderDetail.setUserId(user.getUserId());
            orderDetail.setUserName(user.getDisplayName());
            // 课程id
            orderDetail.setCourseId(courseId);
            // 课程名
            orderDetail.setCourseName(cou.getCourseName());
            // 订单id
            orderDetail.setOrderId(order.getOrderId());
            // 订单请求号
            orderDetail.setOrderNo(order.getOrderNo());
            /*商品类型*/
            orderDetail.setOrderType(OrderType.COURSE.toString());
            // 到期时间
            orderDetail.setAuthDate(cou.getExpireDate());
            // 下单时间
            orderDetail.setCreateTime(date);
            // 课程原始价格
            orderDetail.setSourcePrice(cou.getSourcePrice());
            // 课程实际支付价格
            orderDetail.setPrice(cou.getPrice());
            // 课程状态
            orderDetail.setAuthStatus(OrderStatus.SUCCESS.toString());
            orderDetail.setPayTime(date);
            orderDetail.setUpdateTime(date);
            orderDetail.setDescription("课程卡使用(" + cardCode.getCardCode() + ")");
            orderDetailService.insert(orderDetail);
            userBuyService.create(orderDetail);
            courseService.updateBuy(cou.getCourseId());
        }
        // 课程卡信息改变
        cardCode.setUserId(user.getUserId());
        cardCode.setUserName(user.getDisplayName());
        cardCode.setOrderId(order.getOrderId());
        cardCodeService.updateUsed(cardCode);
        return AjaxResult.success();
    }
}